<template>
    <view class="purchase">
        <view class="purchase_heder" wx:if="{{address}}" @tap="urlTo('/pages/common/address?type=purchase')">
            <view class="purchase_dingwei"><i class="iconfont icon-dingwei"></i></view>
            <view class="purchase_fix">
                <view class="purchase_fix_erzi">
                    <view>收货人：</view>
                    <view>{{address.name}}</view>
                    <view>{{address.phone}}</view>
                </view>
                <view>{{address.provinceName+address.cityName+address.areaName+address.address}}</view>
            </view>
            <view class="purchase_jiantou"><i class="iconfont icon-jiantou"></i></view>
        </view>
        <view class="purchase_heder"  wx:if="{{!address}}" @tap="urlTo('/pages/common/address?type=purchase')">
            <view class="purchase_fix vimi">
                <view>添加收货地址</view>
            </view>
            <view class="purchase_jiantou fr"><i class="iconfont icon-jiantou"></i></view>
        </view>
        <view class="purchase_shangping">
            <view class="purchase_next">
                <view class="purchase_img">
                    <image src="{{detail.topicImage }}"></image>
                </view>
                <view class="shangping">
                    <view>{{detail.name}}</view>
                    <view>{{detail.code}}</view>
                    <view>
                        <text>{{detail.size}}码</text>
                    </view>
                </view>
                <view class="porigth">￥{{detail.minSellerOfferAmount}}</view>
            </view>
            <view class="purchase_fot" wx:if="{{address}}">
                <view class="border-top"></view>
                <view>{{kdprice.logisticsName}}</view>
                <view>￥{{kdprice.amount}}</view>
            </view>
            <view class="purchase_fot">
                <view class="border-top"></view>
                <view>合计支付</view>
                <view wx:if="{{!hasCou}}">￥{{(detail.minSellerOfferAmount*100+kdprice.amount*100)/100}}</view>
                <view wx:elif="{{hasCou && getCoupon.couponType == '现金优惠'}}">￥{{xjPrice}}</view>
                <view wx:elif="{{hasCou && getCoupon.couponType != '现金优惠'}}">￥{{detail.minSellerOfferAmount}}</view>
            </view>
        </view>
        <view class="weixinAndzhifubao">
            <view class="boxfix" @tap="changePay('WX_MINI')">
                <view class="iconWis"><i class="iconfont icon-weixinzhifu2"></i></view>
                <text>微信支付</text>
                <view class="xuanze">
                    <i class="iconfont icon-yuancircle46 xuanze_color_quan" wx:if="{{!getPaySure}}"></i>
                    <i class="iconfont icon-dui xuanze_color_dui" wx:if="{{getPaySure}}"></i>
                </view>
            </view>
            <!--<view class="boxfix" @tap="changePay('ALIPAY')">
                <view class="iconWis"><i class="iconfont icon-zhifubao"></i></view>
                <text>支付宝支付</text>
                <view class="xuanze">
                    <i class="iconfont icon-yuancircle46 xuanze_color_quan" wx:if="{{getPaySure}}"></i>
                    <i class="iconfont icon-dui xuanze_color_dui" wx:if="{{!getPaySure}}"></i>
                </view>
            </view>-->
        </view>
        <!-- 使用优惠券 -->
        <view class="useDiscounts">
            <navigator url="/pages/personalCenter/coupons?type=FREE_SHIP" wx:if="{{!hasCou}}">
                <checkbox-group class="useDiscounts_one" bindchange="change">
                    <checkbox wx:if="{{!changeCou}}" checked="{{changeCou}}"/>
                    <checkbox wx:if="{{changeCou}}" checked="{{!changeCou}}"/>
                </checkbox-group>
                <text class="useDiscounts_one_text">使用优惠券</text>
            </navigator>
            <view wx:if="{{hasCou}}">
                <checkbox-group class="useDiscounts_to" bindchange="change">
                    <checkbox checked="{{hasCou}}"/>
                </checkbox-group>
                <view class="useDiscounts_to_text" wx:if="{{getCoupon.couponType == '现金优惠'}}">
                    使用{{getCoupon.couponType}}劵 ，可用余额：<text class="shareColor">{{getCoupon.couponAmount}}</text>元
                </view>
                <view class="useDiscounts_to_text" wx:if="{{getCoupon.couponType != '现金优惠'}}">
                    使用{{getCoupon.couponType}}劵
                </view>
            </view>
        </view>
        <!-- 使用优惠券 end -->
        <view class="quanxian">
            鉴于商品价格波动性，同时每个款式每个尺码的商品出售时仅有一件等情况，故不支持退换货。
        </view>
        <view class="youhuiquan_pay">
            <view class="youhuiquan_btn">
                <checkbox-group bindchange="changeTwo">
                    <checkbox value="{{check}}" checked="{{check}}" />
                </checkbox-group>
            </view>
            <view class="youhuiquan_text">
                <text>我已阅读并同意</text>
                <text style="  color: #ffb025;margin-left: 20rpx;" @tap="urlTo('/pages/tj/introBuy')">购买协议</text>
            </view>
        </view>
        <view class="pa-20">
            <button class="button type_main" @tap="submitForm">立即支付</button>
        </view>
    </view>
</template>
<script>
    import wepy from 'wepy';
    import tip from '@/utils/tip'
    import api from '@/api/api';
    import { GOODSDETAIL, CHOOSECOU } from '@/utils/constant';

    export default class purchase extends wepy.page {
        config = {  // 配置当前页面
            navigationBarTitleText: '确认订单'    // 头部标题
        };
        components = {};

        data = {
            userId:'',
            detail:'',
            form:{},
            getPaySure:true,
            getPayType:'WX_MINI',
            address:'',
            kdprice:{
                amount:0
            },
            hasCou:false,
            getCoupon:'',
            check:true,
            changeCou:false,
            xjPrice:0
        };
        methods = {  // 方法
            urlTo(url) {
                wx.navigateTo({
                    url: url
                })
            },
            changePay(r){
                const t = this;
                if(r == 'WX_MINI'){
                    t.getPaySure = true;
                    t.getPayType = r;
                }else {
                    t.getPaySure = false;
                    t.getPayType = r;
                }
            },
            submitForm(){
                const t = this;
                if (!t.check) {
                    tip.alert('请同意购买协议')
                } else {
                    t.wxLogin()
                }
            },
            change(){
                const t = this;
                t.changeCou = t.changeCou ? false : true;
                t.hasCou = false;
                t.getCoupon = '';
                wx.removeStorageSync(CHOOSECOU);
                t.$apply();
            },
            changeTwo(e) {
                const t = this
                let c = e.detail.value
                if (c[0]) {
                    t.check = true
                } else {
                    t.check = false
                }
            }
        };
        events = {};
        /**
         * 获取商品详情
         * @returns {Promise.<void>}
         */
        async getChildCate() {
            const t = this;
            const a = await api.goodsDetail({
                query:t.form
            });
            if (a.data.code == 0) {
                t.detail = a.data.data;
                t.$apply();
            } else {
                tip.error(a.data.msg);
            }
        }
        /**
         * 提交订单
         * @returns {Promise.<void>}
         */
        async subFormApi() {
            const t = this;
            let d = {};
            d['addressId'] = t.address.id;
            d['goodsId'] = t.detail.id;
            d['logisticsCode'] = t.detail.kdLog.code;
            d['minSellerOfferId'] = t.detail.minSellerOfferId;
            d['size'] = t.detail.size;
            d['userId'] = t.userId;
            if(t.getCoupon&&t.hasCou){
                d.couponId = t.getCoupon.id;
            }
            const a = await api.orderBuyImme({
                query:d,
                method:'POST'
            });
            if (a.data.code == 0) {
                if(a.data.data.state=='WAIT_PAY'){
                    t.toPayFun(a.data.data);
                }else {
                    wepy.switchTab({
                        url: '/pages/main/main'
                    })
                }
            } else {
                tip.error(a.data.msg);
            }
        }
        /**
         * 获取地址
         * @returns {Promise.<void>}
         */
        async addressApi(k) {
            const t = this;
            const a = await api.defaultAddress({},t.userId);
            if (a.data.code == 0) {
                let l = a.data.data,
                check = l.length;
                l.forEach((r)=>{
                    if(r.id == k){
                        t.address = r;
                        t.getLogisticsPriceFun();
                    }else {
                        check--;
                    }
                });
                if(check<=0){
                    t.address = '';
                }
                t.$apply();
            } else {
                t.address = '';
                t.$apply();
                tip.error(a.data.msg);
            }
        }
        /**
         * 获取物流费用
         * @returns {Promise.<void>}
         */
        async getLogisticsPriceFun() {
            const t = this;
            const a = await api.getLogisticsPrice({
                query:{
                    logisticsCode: t.detail.kdLog.code,
                    addressId:t.address.id
                }
            });
            if (a.data.code == 0) {
                let l = a.data.data;
                if(l.deft){
                    t.kdprice = l;
                    t.xjPrice = (t.detail.minSellerOfferAmount*100+t.kdprice.amount*100-t.getCoupon.couponAmount*100)/100;
                    if(t.xjPrice < 0){
                        t.xjPrice = 0;
                    }
                }else {
                    tip.alert('此快递不是默认快递！',3000);
                }
                t.$apply();
            } else {
                tip.error(a.data.msg);
            }
        }
        onShow(){
            const t = this;
            let detail = wx.getStorageSync(GOODSDETAIL);
            let userId = wx.getStorageSync('userId');
            let coupon = wx.getStorageSync(CHOOSECOU);
            let paId = wx.getStorageSync('purOrderAddressId');
            if (detail) {
                t.detail = detail;
                if (userId) {
                    t.userId = userId;
                }
                if(coupon){
                    t.hasCou = true;
                    t.getCoupon = coupon;
                }else {
                    t.hasCou = false;
                }
                if(paId){
                    t.addressApi(paId);
                }else {
                    t.address = '';
                }
            }
            t.$apply();
        }
        // 获取唯一标识openId
        async getmyOpenid(a) {
            const t = this;
            const json = await api.getOpenid({
                query:{}
            },'userId='+t.userId+'&code='+a);
            if (json.data.code == 0) {
                t.subFormApi();
            } else {
                tip.error(json.data.msg);
            }
        }
        // 微信登录
        async wxLogin() {
            const t = this;
            let adId = t.address.id;
            if(!adId){
                tip.alert('请选择收货地址',3000);
            }else {
                wx.login({
                    success: function(res) {
                        if (res.code) {
                            t.getmyOpenid(res.code)
                        } else {
                            tip.error(res.msg)
                        }
                    }
                })
            }
        }
        /**
         * 去支付
         * @returns {Promise.<void>}
         */
        async toPayFun(r) {
            const a = await api.orderTrade({
                query:{
                    userId:r.buyerId,
                    orderId:r.id,
                    orderType:'GOODS',
                    payType:'WX_MINI'
                },
                method:'POST'
            });
            if (a.data.code == 0) {
                // 微信支付
                wx.requestPayment({
                    timeStamp: a.data.data.wxpayPamram.timeStamp,
                    nonceStr: a.data.data.wxpayPamram.nonceStr,
                    package: a.data.data.wxpayPamram.package,
                    signType: 'MD5',
                    paySign: a.data.data.wxpayPamram.paySign,
                    success:function(){
                        tip.success('支付成功！！',2000);
                        wx.removeStorageSync('purOrderAddressId');
                        wx.removeStorageSync(CHOOSECOU);
                        wepy.switchTab({
                            url: "/pages/main/main"
                        });
                    }
                })
            } else {
                tip.error(a.data.msg);
            }
        }
    }

</script>
<style lang="less">
    .purchase {
        .useDiscounts {
            padding: 20rpx;
            .useDiscounts_one {
                display: inline-block;
                vertical-align: middle;
            }
            .useDiscounts_one_text {
                display: inline-block;
                vertical-align: middle;
            }
            .useDiscounts_to {
                display: inline-block;
                vertical-align: middle;
            }
            .useDiscounts_to_text {
                display: inline-block;
                vertical-align: middle;
            }
        }
        .purchase_heder {
            background: #fff;
            display: flex;
            padding: 40rpx 0;
            .purchase_dingwei {
                width: 100rpx;
                text-align: center;
                i {
                    font-size: 50rpx;
                }
            }
            .purchase_fix {
                .purchase_fix_erzi {
                    width: 580rpx;
                    display: flex;
                    color: #333;
                    view:last-child {
                        margin-left: auto;
                    }
                }
            }
            .vimi{
                vertical-align: center;
                padding-left: 20rpx;
            }
            .purchase_jiantou {
                width: 50rpx;
                text-align: right;
            }
            .fr{
                flex: 1;
                padding-right: 30rpx;
            }
        }
        .purchase_shangping {
            background: #fff;
            .purchase_next {
                display: flex;
                padding: 40rpx 20rpx;
                margin-top: 20rpx;
                position: relative;
                .purchase_img {
                    width: 250rpx;
                    height: 180rpx;
                    text-align: center;
                    image {
                        width: 180rpx;
                        height: 180rpx;
                        margin: 0 auto;
                        text-align: center;
                        border: 1px solid #ddd;

                    }
                }
                .shangping {
                    width: 580rpx;
                    position: relative;
                    view:last-child {
                        position: absolute;
                        left: 0;
                        bottom: 0;
                    }
                }
                .porigth {
                    position: absolute;
                    right: 40rpx;
                    bottom: 30rpx;
                }
            }
            .purchase_fot {
                display: flex;
                padding: 40rpx 40rpx 40rpx 40rpx;
                position: relative;
                view:last-child {
                    margin-left: auto;
                }
                .border-top {
                    position: absolute;
                    top: 0;
                    right: 0;
                    height: 1rpx;
                    width: 720rpx;
                    background: #ddd;
                }
            }
        }

        .weixinAndzhifubao {
            margin-top: ~'20rpx';
            background: #fff;
            padding-left: ~'20rpx';
            border-bottom: 1px solid #ddd;
            border-top: 1px solid #ddd;
            .boxfix {
                height: ~'100rpx';
                line-height: ~'100rpx';
                padding-right: ~'30rpx';
                display: flex;

                .iconWis {
                    text-align: center;
                    width: ~'70rpx';
                    .icon-weixinzhifu2 {
                        color: #3cb034;
                    }
                    .icon-zhifubao {
                        color: #108ee9;
                    }
                    i {
                        font-size: 20px;
                    }
                }
                text {
                    margin-right: auto;
                }
                .xuanze {
                    .xuanze_color_quan {
                        color: #333;
                        font-size: 18px;
                    }
                    .xuanze_color_dui {
                        color: orange;
                    }
                }
            }
            text {
                padding-left: ~'20rpx';
                font-size: ~'28rpx';
            }

        }
        .quanxian {
            padding: ~'20rpx';
            font-size: ~'26rpx';
            margin-top: ~'40rpx';
            text {
                display: block;
                margin-top: ~'20rpx';
            }
        }
        .pa-20{
            padding: ~'20rpx';
        }
        .youhuiquan_pay {
            padding: 20rpx;
            .youhuiquan_btn {
                display: inline-block;
                vertical-align: middle;
            }
            .youhuiquan_text {
                display: inline-block;
                vertical-align: middle;
            }
        }
    }
</style>
